package org.elsfs.domain.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import jakarta.inject.Singleton;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.elsfs.domain.entity.SysUser;
import org.elsfs.domain.manager.SysUserManager;
import org.elsfs.domain.mapper.SysUserMapper;

/**
 * 用户管理mybatis实现
 *
 * @author zeng
 * @since 0.0.1
 */
@Singleton
@RequiredArgsConstructor
@Named(SysUserManager.BEAN_NAME)
public class SysUserServiceImpl implements SysUserManager {

  @Inject protected final SysUserMapper sysUserMapper;

  @Override
  public SysUser getUserByUsername(String username) {
    return getUserByUsername(username, true);
  }

  protected SysUser getUserByUsername(String username, boolean isCache) {
    SysUser user =
        sysUserMapper.selectOne(
            Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUsername, username));
    return user;
  }

  @Override
  public SysUser getUserByPhone(String phone) {
    return sysUserMapper.selectOne(
        Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getPhone, phone));
  }

  @Override
  public SysUser getUserByUserId(String userId) {
    return sysUserMapper.selectOne(
        Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUserId, userId));
  }

  @Override
  public SysUser getUserByEmail(String email) {
    return sysUserMapper.selectOne(
        Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getEmail, email));
  }

  @Override
  public SysUser createUser(SysUser user) {
    sysUserMapper.insert(user);
    return user;
  }

  @Override
  @Transactional(rollbackOn = Exception.class)
  public SysUser updateUser(SysUser user) {
    sysUserMapper.updateById(user);
    return user;
  }

  @Override
  public boolean deleteUser(SysUser user) {
    boolean remove = SqlHelper.retBool(sysUserMapper.deleteById(user));
    return remove;
  }

  @Override
  public boolean deleteUserByUsername(String username) {
    SysUser sysUser = getUserByUsername(username, false);
    return SqlHelper.retBool(sysUserMapper.deleteById(sysUser));
  }

  @Override
  public boolean deleteUserByUserId(String userId) {
    SysUser sysUser = getUserByUserId(userId);
    boolean remove = false;
    if (sysUser != null) {
      remove = SqlHelper.retBool(sysUserMapper.deleteById(sysUser));
    }
    return remove;
  }
}
